package com.jackie.proximity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

/**
 * Created by zhuweiping on 5/16/15.
 */
public class ProximitySensor implements SensorEventListener {
    private static final String TAG = ProximitySensor.class.getSimpleName();
    private Context mContext;

    public ProximitySensor(Context context) {
        super();
        mContext = context;
    }

    /**
     * Called when sensor values have changed.
     * <p>See {@link SensorManager SensorManager}
     * for details on possible sensor types.
     * <p>See also {@link SensorEvent SensorEvent}.
     * <p/>
     * <p><b>NOTE:</b> The application doesn't own the
     * {@link SensorEvent event}
     * object passed as a parameter and therefore cannot hold on to it.
     * The object may be part of an internal pool and may be reused by
     * the framework.
     *
     * @param event the {@link SensorEvent SensorEvent}.
     */
    @Override
    public void onSensorChanged(SensorEvent event) {

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext.getApplicationContext());
        String url = preferences.getString(MainActivity.URL, "");
        if(TextUtils.isEmpty(url)) {
            return;
        }

        float status = event.values[0];
        Log.i(TAG, "onSensorChanged& status is " + status);
        if(status == Float.valueOf("0")) {
            Intent intent = new Intent(mContext, WebActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Log.i(TAG, "onSensorChanged& start load " + url);
            mContext.startActivity(intent);
        } else {
            Log.i(TAG, "onSensorChanged& nothing");
        }
    }

    /**
     * Called when the accuracy of the registered sensor has changed.
     * <p/>
     * <p>See the SENSOR_STATUS_* constants in
     * {@link SensorManager SensorManager} for details.
     *
     * @param sensor
     * @param accuracy The new accuracy of this sensor, one of
     *                 {@code SensorManager.SENSOR_STATUS_*}
     */
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}
